#!/bin/bash
function help {
	echo "Required Environment:" >&2
	echo "  REPLICATION_MANAGER_USER" >&2
	echo "  REPLICATION_MANAGER_PASSWORD" >&2
	echo "  REPLICATION_MANAGER_URL" >&2
	echo "  REPLICATION_MANAGER_CLUSTER_NAME" >&2
	echo "  REPLICATION_MANAGER_HOST_NAME" >&2
	echo "  REPLICATION_MANAGER_HOST_PORT" >&2
}
[ -z $REPLICATION_MANAGER_USER ] && help && exit 1
[ -z $REPLICATION_MANAGER_PASSWORD ] && help && exit 1
[ -z $REPLICATION_MANAGER_URL ] && help && exit 1
[ -z $REPLICATION_MANAGER_CLUSTER_NAME ] && help && exit 1
[ -z $REPLICATION_MANAGER_HOST_NAME ] && help && exit 1
[ -z $REPLICATION_MANAGER_HOST_PORT ] && help && exit 1

GET="wget -q --no-check-certificate -O- --header Content-Type:application/json"
AUTH_DATA="{\"username\": \"$REPLICATION_MANAGER_USER\", \"password\": \"$REPLICATION_MANAGER_PASSWORD\"}"
TOKEN=$($GET --post-data "$AUTH_DATA" --header Accept:text/html $REPLICATION_MANAGER_URL/api/login)
function get {
	$GET --header Accept:application/json --header "Authorization: Bearer $TOKEN" $@
}

get $REPLICATION_MANAGER_URL/api/clusters/$REPLICATION_MANAGER_CLUSTER_NAME/servers/$REPLICATION_MANAGER_HOST_NAME/$REPLICATION_MANAGER_HOST_PORT/need-config-fetch > need-config-fetch
if [ $? -eq 0 ]; then
	get $REPLICATION_MANAGER_URL/api/clusters/$REPLICATION_MANAGER_CLUSTER_NAME/servers/$REPLICATION_MANAGER_HOST_NAME/$REPLICATION_MANAGER_HOST_PORT/config > config.tar.gz
	if [ $? -eq 0 ]; then
		rm -rf  /bootstrap/etc /bootstrap/init
		cat config.tar.gz  | tar xzvf - -C /bootstrap
		rm -f config.tar.gz
	fi
	chown -R 999:999 /bootstrap/data
	chmod -R 0755 /bootstrap/init

fi

CURRENT_VERSION=$(cat /bootstrap/version)
if [ -z "$CURRENT_VERSION" ]; then
	CURRENT_VERSION="0.0.0"
fi

get $REPLICATION_MANAGER_URL/api/version > version
mkdir -p /bootstrap
MONITOR_VERSION=$(cat version)

# If the version is not the same or the file not exists, download the new version
if [ "$MONITOR_VERSION" != "$CURRENT_VERSION" ] || [ ! -f /bootstrap/replication-manager-cli ]; then
	echo $MONITOR_VERSION > /bootstrap/version
	
	get $REPLICATION_MANAGER_URL/static/configurator/bin/replication-manager-cli > /bootstrap/replication-manager-cli
	if [ $? -eq 0 ]; then
		cp /bootstrap/replication-manager-cli /bootstrap/init/replication-manager-cli
		chmod +x /bootstrap/init/replication-manager-cli
	fi
else
	# If the file exists, copy it to the init directory
	if [ -f /bootstrap/replication-manager-cli ] && [ ! -f /bootstrap/init/replication-manager-cli ]; then
		cp /bootstrap/replication-manager-cli /bootstrap/init/replication-manager-cli
		chmod +x /bootstrap/init/replication-manager-cli
	fi
fi